package com.ruge.test.网易云;

import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.GetObjectRequest;
import com.netease.cloud.services.nos.model.NOSObject;
import com.netease.cloud.services.nos.model.ObjectMetadata;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.*;
import java.net.URL;

/**
 * 爱丽丝、如歌  创建于 2018/9/2 10:03
 * 说明:  TODO
 */
public class 对象存储_下载 {
	/**
	 * 流式下载
	 */
	@Test
	public void test1() {
		String accessKey = "4046a66045934bc6b366c0d3e995aceb";
		String secretKey = "1320ab11b4cb4c9c82b8404d0dce891e";
		Credentials credentials = new BasicCredentials(accessKey, secretKey);
		NosClient nosClient = new NosClient(credentials);
		NOSObject nosObject = nosClient.getObject("ruge-security", "ruge-security/headPhoto/demo1.png");
//可以通过NOSObject对象的getObjectMetadata方法获取对象的ContentType等元数据信息
		String contentType = nosObject.getObjectMetadata().getContentType();
//流式获取文件内容
		InputStream in = nosObject.getObjectContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		while (true) {
			String line;
			try {
				line = reader.readLine();
				if (line == null) {
					break;
				}
				System.out.println("\n" + line);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载到本地文件
	 */
	@Test
	public void test2() {
		try {
			URL url = new URL("http://ruge-security.nos-eastchina1.126.net/ruge-security/headPhoto/demo1.png");
			File file = new File("e:/baidu1.png");
			FileUtils.copyURLToFile(url, file);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
